package com.dhl.config;

import com.dhl.commonutils.security.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.annotation.Resource;

/**
 * @title: SecurityConfig
 * @Author danghailiang
 * @Date: 2022/10/14 20:44
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity // 开启安全配置
// 启用 prePostEnabled 注解配置
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 登录成功处理器
     */
    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    /**
     * 登录失败处理器
     */
    @Resource
    private LoginFailureHandler loginFailureHandler;
    /**
     * 自定义登录处理服务
     */
    @Resource
    private MyUserUserDetailsServiceImpl myUserUserDetailsService;
    /**
     * jwt 自定义认证失败处理
     */
    @Resource
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    /**
     * 登出处理器
     */
    @Resource
    private JwtLogoutHandler jwtLogoutHandler;
    /**
     * 密码加密处理器
     */
    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager());
        return jwtAuthenticationFilter;
    }


    /**
     * URL 白名单
     */
    public static final String[] URL_WHITELIST = {
            "/login",
            "/logout",
            "/captcha",
            "/password",
            "/image/**",
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 开启跨域 和 csrf攻击 关闭
        http
                .cors()
                .and()
                .csrf()
                .disable()

                // 登录配置
                .formLogin()
                // 登录配置
                .successHandler(loginSuccessHandler)
                // 登录失败处理
                .failureHandler(loginFailureHandler)
                .and()
                // 登出处理
                .logout()
                .logoutUrl("/user/logout")
                // 登出配置
                .logoutSuccessHandler(jwtLogoutHandler)

                // session禁用配置
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                // 拦截规则配置
                .and()
                .authorizeRequests()
                // 放行白名单
                .antMatchers(URL_WHITELIST)
                // 复制所有权限
                .permitAll()
                // 其他路径进行认证
                .anyRequest()
                .authenticated()

                .and()
                // 异常处理器配置
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)

                .and()
                // 自定义过滤器配置
                .addFilter(jwtAuthenticationFilter());
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 切换到自定义服务类处理登录
        auth.userDetailsService(myUserUserDetailsService);
        super.configure(auth);
    }
/*    @Override
    public void init(WebSecurity web) throws Exception {
//        web.ignoring()
//               .antMatchers(URL_WHITELIST);
//        HttpSecurity http = this.getHttp();
//        web.addSecurityFilterChainBuilder(http).postBuildAction(() -> {
//            FilterSecurityInterceptor securityInterceptor = (FilterSecurityInterceptor)http.getSharedObject(FilterSecurityInterceptor.class);
//            web.securityInterceptor(securityInterceptor);
//        });
    }*/

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/static/image/**"
        );
//        super.configure(web);
    }
}
